package com.loansystem.controller;

import com.loansystem.bean.user.User;
import com.loansystem.service.user.UserService;
import com.loansystem.utils.FileUpload;
import com.loansystem.utils.MailService;
import com.loansystem.utils.RandomNumUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

@Controller
public class PublicController {
    @Autowired
    UserService userService;
    @Autowired
    MailService mailService;
    //随机验证码
    private String randomNum = "";


    //登录页
    @RequestMapping({"/gologin", "/"})
    public String goLogin() {
        return "login";
    }

    //去注册页面
    @RequestMapping("/goregister")
    public String goRegister() {
        return "register";
    }


    //注销
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    //主页面,登录
    @RequestMapping("/goindex")
    public String login(String user_mail, String user_pwd, Model model) {
        System.out.println(user_mail + "--" + user_pwd);
        User user = userService.getUserByUsername(user_mail);
        if (user.getUser_state() == 0) {
            model.addAttribute("msg", "账号未激活");
            return "login";
        } else if (user.getUser_state() == 2) {
            model.addAttribute("msg", "账号已注销");
            return "login";
        }
        //保存用户信息
        model.addAttribute("user",user);
//        session.setAttribute("user",user);

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user_mail, user_pwd);
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户账号输入错误");
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误，请重新输入");
            return "login";
        }
    }

//    //头像上传修改
//    @RequestMapping("uploadImg")
//    @ResponseBody
//    public String upload_Userimg(@RequestParam("userImg") MultipartFile multipartFile){
//        FileUpload.doSingleFileUpload(multipartFile,"images/user","userImg",User.class,"user_img");
//        System.out.println(multipartFile.getOriginalFilename());
//        return "OK";
//    }

    //注册
    @RequestMapping("/regsiter")  //, @RequestParam("userImg") MultipartFile multipartFile
    public String register(User user, @RequestParam("userImg") MultipartFile multipartFile,Model model) {
//        System.out.println(user);
        User user1 = userService.getUserByUsername(user.getUser_mail());
        if (user1 != null) {
            model.addAttribute("msg", "该账户已注册");
            return "register";
        }
        //上传头像
        FileUpload.doSingleFileUpload(multipartFile,"images/user","userImg",user,"user_img");
        System.out.println("=============图片路径===============");
        System.out.println(user.getUser_img());
        System.out.println("=============================");
        int i = userService.addUser(user);
        if (i > 0) {
            System.out.println("注册成功");
            model.addAttribute("user_mail", user.getUser_mail());
            randomNum = RandomNumUtil.getRandomNum();
            System.out.println("验证码为："+randomNum);
            mailService.sendMail(user.getUser_mail(), "账号激活", randomNum);
            return "goActivation";
        } else {
            model.addAttribute("msg", "注册失败");
            return "register";
        }
    }

    //重新获取验证码
    @RequestMapping("getCode")
    @ResponseBody
    public String reRandomNum(String user_mail) {
        randomNum = RandomNumUtil.getRandomNum();
        System.out.println("验证码为："+randomNum);
        mailService.sendMail(user_mail, "账号激活", randomNum);
        return "OK";
    }

    //去激活页
    @RequestMapping("goActivation")
    public String goActivation() {
        return "goActivation";
    }

    //激活账号
    @RequestMapping("/activation")
    @ResponseBody
    public String activation(@RequestParam("key") String key, @RequestParam("user_mail") String user_mail, Model model) {
        System.out.println("key--" + key);
        System.out.println("user_mail--" + user_mail);
        System.out.println("randomNum--" + randomNum);
        //获取用户 ， 用户id用于激活
        User user = userService.getUserByUsername(user_mail);
        if (key.equals(randomNum)) {
            int i = userService.updataByUserId(user.getUser_id());
            if (i > 0) {
                System.out.println("激活成功");
                model.addAttribute("state", "激活成功");
                return "true";
            } else {
                model.addAttribute("msg", "激活失败");
                return "false";
            }
        } else {
            model.addAttribute("msg", "激活失败");
            return "false";
        }
    }

    //去密码找回页
    @RequestMapping("goFindPwd")
    public String goFindPwd() {
        return "findPwd";
    }

    //密码找回
    @RequestMapping("findPwd")
    @ResponseBody
    public String findPwd(@RequestParam("mail") String mail, @RequestParam("code") String code, @RequestParam("pwd") String pwd) {
        if (mail == "" || code == "" || pwd == "") {
            return "false";
        }
        User user = userService.getUserByUsername(mail);
        if (user != null && code.equals(randomNum)) {
            int i = userService.updataPwd(pwd, user.getUser_id());
            if (i > 0) {
                return "true";
            }else{
                return "false";
            }
        }else {
            return "false";
        }
    }
}
